package com.zhou.Controller;

import com.zhou.domain.DTO.UserLoginDTO;
import com.zhou.domain.DTO.UserUpdateDTO;
import com.zhou.domain.Rusult;
import com.zhou.domain.User;
import com.zhou.server.impl.OnlineUserService;
import com.zhou.server.impl.UserServerImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
public class UserController {

    @Autowired
    private UserServerImpl userServer;

    @Autowired
    private OnlineUserService onlineUserService;

    //根据ID查询
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询")
    public String select(@PathVariable int id){
        System.out.println("id = "+id);
        User user = userServer.getById(id);
        return user.toString();
    }


    //添加用户
    @PostMapping("/save")
    @ApiOperation("添加用户")
    public String save2(@RequestBody UserUpdateDTO user2){
        User user = new User();
        BeanUtils.copyProperties(user,user2);
        String result = userServer.save(user);
        return result;
    }


    //修改用户
    @PutMapping("/save")
    @ApiOperation("修改用户")
    public String save(@RequestBody UserUpdateDTO user){
        //String result = userServer.save(user);
        User user1 = new User();
        BeanUtils.copyProperties(user,user1);
        userServer.updata(user1);
        return "result";
    }

    //删除用户
    @DeleteMapping("/delete/{id}")
    @ApiOperation("根据ID删除用户")
    public Rusult delete(@PathVariable int id){
        userServer.delete(id);
        return Rusult.success();
    }

    //用户登录
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Rusult login(@RequestBody UserLoginDTO userLoginDTO){
        String rusult = userServer.login(userLoginDTO);
        onlineUserService.userLogin(userLoginDTO.getName());
        return Rusult.success(rusult);
    }

    //用户登录
    @ApiOperation("退出登录")
    @PostMapping("/loginout")
    public Rusult loginOut(@RequestBody UserLoginDTO userLoginDTO){
        onlineUserService.userLogout(userLoginDTO.getName());
        return Rusult.success("退出登录");
    }

    //获取当前登录用户列表
    @ApiOperation("获取当前登录用户列表")
    @GetMapping("/getloginuser")
    public Rusult getLoginUser(){
        return Rusult.success(onlineUserService.getOnlineUsers());
    }

}
